package com.lanou3g.code0420;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Scanner;

/**
 * If there are no bugs, it was created by Chen FengYao on 2018/4/20;
 * Otherwise, I don't know who created it either
 */

public class Main {
    public static void main(String[] args) {
        // TCP 客户端
        // 使用无参数构造方法
        // 这个socket对象会自动绑定本地的一个没有被使用的端口号
        Socket socket = new Socket();
        PrintWriter pw = null;
        Scanner scanner = new Scanner(System.in);

        try {
            // 让socket客户端链接到远程服务器
            // 需要指定 服务器的IP地址和端口号
            socket.connect(
                    new InetSocketAddress("127.0.0.1"
                            ,2333));

            // 开启线程来读数据
            new ReadThread(socket).start();

            OutputStream os = socket.getOutputStream();
            pw = new PrintWriter(
                    new OutputStreamWriter(os));

            while (true) {
                String line = scanner.nextLine();
                pw.println(line);
                pw.flush();
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (pw != null){
                pw.close();
            }
            // socket对象使用完成后 也需要关闭
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            scanner.close();// scanner 使用完成后关闭

        }
    }
}
